#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/06/27
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from project.flasky import db
from project.define import db_logger


DataName = "闸机"
TableName = "app_device_gate"

class DeviceGate(db.Model):
    """
    闸机信息
    """
    __tablename__ = TableName
    # 设备编号
    GateID = db.Column(db.String(16), primary_key=True, nullable=False)
    # 闸机类型:Entrance/Exit/All
    GateType = db.Column(db.String(16), nullable=False)
    # 闸机名称
    GateName = db.Column(db.String(16), nullable=False)
    # 功能
    GateMethods = db.Column(db.String(32),nullable=False)
    # 闸机位置
    Position = db.Column(db.String(32))
    # 闸机地址
    GateAddr = db.Column(db.String(16), unique=True)
    # 闸机组
    GateGroup = db.Column(db.String(16))
    # 主板信息
    Board = db.Column(db.String(16))
    # 闸机版本
    Version = db.Column(db.String(8))

    def __init__(self, **kwargs) -> None:
        super().__init__()
        self.GateID = kwargs.get('GateID')
        self.GateType = kwargs.get('GateType')
        self.GateName = kwargs.get('GateName')
        self.GateMethods = kwargs.get('GateMethods')
        self.Position = kwargs.get('Position')
        self.GateAddr = kwargs.get('GateAddr')
        self.GateGroup = kwargs.get('GateGroup')
        self.Board = kwargs.get('Board')
        self.Version = kwargs.get('Version')

    def gate_methods_name(self, **kwargs):
        """
        闸机功能名称
        """
        if "," in self.GateMethods:
            gate_methods = self.GateMethods.split(",")
        else:
            gate_methods = [self.GateMethods]
        methods = [kwargs.get(i) for i in gate_methods]
        if len(methods) > 1:
            return ",".join(methods)
        elif len(methods) == 1:
            return methods[0]

    def to_dict(self):
        """
        转换键值对
        """
        def convert_data(name):
            val = getattr(self, name)
            if name == "GateMethods":
                if "," in val:
                    val = val.split(",")
                else:
                    val = [val,]
            return val

        return dict([(c.name, convert_data(c.name)) for c in self.__table__.columns])

    @staticmethod
    def current_datas():
        """
        当前闸机
        """
        gates = DeviceGate.query.all()
        if gates:
            return [i.to_dict() for i in gates]
        return []

    @staticmethod
    def selected_data(**kwargs):
        """
        选中数据
        """
        gate_id = kwargs.get('GateID')
        if gate_id:
            return DeviceGate.query.filter_by(GateID=gate_id).first()

    @staticmethod
    def columns_name():
        """
        数据表标题
        """
        ColumnName = {
            'GateID': '閘機ID', 'GateType': '閘機類型', 'GateName': '閘機名稱', 'GateMethods': '閘機功能', 'GateAddr': 'IP地址', 'Position': '閘機位置',
            'GateGroup': '閘機組', 'Board': '主板信息', 'Version': '系統版本'
            }
        return ColumnName

    @staticmethod
    def generate_filters(**kwargs):
        """
        筛选器
        """
        filters = set()
        for k, v in kwargs.items():
            if v:
                if hasattr(DeviceGate, k):
                    if k == 'GateType':
                        filters.add(DeviceGate.GateType == v)
                    elif k == 'GateName':
                        filters.add(DeviceGate.GateName.like(f"%{v}%"))
        return filters

    @staticmethod
    def insert_data(**kwargs):
        """
        新增
        """
        try:
            methods = kwargs.get('GateMethods')
            if isinstance(methods, list):
                kwargs['GateMethods'] = ",".join(methods)
            r = DeviceGate(**kwargs)
            db.session.add(r)
            db.session.commit()
            db_logger.debug(f"{TableName} => 新增{DataName}成功：{kwargs}")
            return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 新增{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def delete_data(**kwargs):
        """
        删除
        """
        try:
            r = DeviceGate.selected_data(**kwargs)
            if r:
                db.session.delete(r)
                db.session.commit()
                db_logger.debug(f"{TableName} => 删除{DataName}D成功：{kwargs}")
                return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 删除{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def modify_data(**kwargs):
        """
        修改
        """
        try:
            update = False
            r = DeviceGate.selected_data(**kwargs)
            if r:
                for k, v in kwargs.items():
                    if hasattr(r, k):
                        if k == 'GateMethods':
                            v = ",".join(v)
                        if getattr(r, k) != v:
                            setattr(r, k, v)
                            update = True
                if update:
                    try:
                        db.session.commit()
                        db_logger.debug(f"{TableName} => 更新{DataName}成功：{kwargs}")
                        return r.to_dict()
                    except Exception as e:
                        db.session.rollback()
                        db_logger.error(f"{TableName} => 更新{DataName}失败：{kwargs} 原因：{e}")
                else:
                    return "ignore"
        except Exception as e:
            db_logger.error(f"{TableName} => 更新{DataName}参数错误：{kwargs} 原因：{e}")

    @staticmethod
    def table_init():
        """
        数据初始化
        """
        demo_data = [
            {'GateID': 'test1', 'GateName': 'P1入口', 'GateType': 'Entrance', 'GateAddr': '192.168.0.20', 'Position': '測試位置1',
            'GateMethods':['LicensePlate','Ticket','Card','Temp']},
            {'GateID': 'test2', 'GateName': 'P1出口', 'GateType': 'Exit', 'GateAddr': '192.168.0.21', 'Position': '測試位置2', 
            'GateMethods':['LicensePlate','Ticket','Card','Temp']},
        ]
        for i in demo_data:
            gate_id = i.get('GateID')
            if gate_id:
                r = DeviceGate.query.filter_by(GateID=gate_id).first()
                if not r:
                    DeviceGate.insert_data(**i)
